#include "usettingsgroup.h"
#include "usettingsitem.h"

#include <QVBoxLayout>
#include <QEvent>

USettingsGroup::USettingsGroup(QWidget *parent)
    : UWidget(parent) , m_layout(new QVBoxLayout)
{
    itemList.clear();
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(6);
    setLayout(m_layout);
}

USettingsGroup::~USettingsGroup()
{
}

void USettingsGroup::insertItem(const int index, USettingsItem *item)
{
    m_layout->insertWidget(index, item);
    itemList.insert(index, item);
    updateLayout();
}

void USettingsGroup::appendItem(USettingsItem *item)
{
    m_layout->addWidget(item);
    itemList.append(item);
    updateLayout();
}

void USettingsGroup::removeItem(USettingsItem *item)
{
    itemList.removeOne(item);
    m_layout->removeWidget(item);
    updateLayout();
}

void USettingsGroup::moveItem(USettingsItem *item, const int index)
{
    const int oldIndex = m_layout->indexOf(item);
    if (oldIndex == index)
        return;

    itemList.removeOne(item);
    m_layout->removeWidget(item);
    m_layout->insertWidget(index, item);
    itemList.insert(index, item);
    updateLayout();
}

void USettingsGroup::setSpacing(const int spaceing)
{
    m_layout->setSpacing(spaceing);
}

int USettingsGroup::itemCount() const
{
    return itemList.size();
}

void USettingsGroup::clear()
{
    itemList.clear();
    const int index = 0;
    const int count = m_layout->count();

    for (int i(index); i != count; ++i) {
        QLayoutItem *item = m_layout->takeAt(index);
        QWidget *w = item->widget();
        w->removeEventFilter(this);
        w->setParent(nullptr);
        delete item;
        w->deleteLater();
    }
}

void USettingsGroup::updateLayout()
{
    int count = itemCount();
    if (1 == count) {
        if (auto item = itemList.front()) {
            item->setItemPosition(QStyleOptionViewItem::ViewItemPosition::OnlyOne);
        }
    } else if (count > 1) {
        for (int i = 0; i < count; ++i) {
            auto item = itemList.at(i);
            if (nullptr == item)
                continue;
            if (0 == i) {
                item->setItemPosition(QStyleOptionViewItem::ViewItemPosition::Beginning);
            } else if ((count -1) == i) {
                item->setItemPosition(QStyleOptionViewItem::ViewItemPosition::End);
            } else {
                item->setItemPosition(QStyleOptionViewItem::ViewItemPosition::Middle);
            }
        }
    }
}

USettingsItem *USettingsGroup::getItem(int index)
{
    if (index < 0)
        return nullptr;

    if (index < itemCount()) {
        return qobject_cast<USettingsItem *>(m_layout->itemAt(index)->widget());
    }

    return nullptr;
}
